//
//  userAccount.swift
//  sina
//
//  Created by 江先铨 on 15/11/11.
//  Copyright © 2015年 jxqstatic. All rights reserved.
//

import UIKit

class userAccount: NSObject,NSCoding {
    //用户的token值  用于调用access_token
    var access_token: String?
    //access_token 的生命周期 单位是秒数
    var expires_in: NSTimeInterval = 0 {
    
        didSet {
         expires_date = NSDate(timeIntervalSinceNow: expires_in) //设置日期的大小
        }
    }

    var expires_date: NSDate?
    //当前授权用户的uid
    var uid: String?
    
   // var remind_in: String?
    
    //用户头像地址 string
    var avatar_large: String?
    //用户名
    var name: String?
    

    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {  }
    
   override var description: String {
    
        let keys = ["access_token","expires_in","uid","avatar_large","name","expires_date"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    
    func saveAccount() { //归档的方法
    
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("accont.plist")
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)  //归档
    }
    
   class  func  loadAccount() -> userAccount? { //这个是 解归档的方法  这个方法是一个类方法
    let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("accont.plist") //路径
    
    if let accout = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? userAccount {
        if accout.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {  //判断用户是否过期 如果是降序的
       
          return accout //解归档
        }
    }
      return nil
}
    

    
    required init?(coder aDecoder: NSCoder) { //归档
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        expires_in = aDecoder.decodeDoubleForKey("expires_in") 
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
    }
    
    func encodeWithCoder(aCoder: NSCoder) { //接档
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expires_date, forKey: "expires_date") //在归档的时候吧数据的归档方式给归档忘写了 导致归档错误
        
    }
}
